<script setup>
import { onMounted, ref, onUnmounted } from "vue";
import { mergeRequest, uploadRequest } from "@/api/sonjs";
const chunkSize = 1024 * 1024 * 10; // 2MB 切片大小
const concurrencyCount = 3; // 并发数

const filerequest = (e) => {
  let file = e.file;
  // console.log(file);
  if (!file) return;
  let fileChunks = [];
  let index = 0; //切片序号

  for (let cur = 0; cur < file.size; cur += chunkSize) {
    fileChunks.push({
      hash: index++,
      chunk: file.slice(cur, cur + chunkSize),
    });
  }
  // console.log(fileChunks);

  // 控制并发和断点续传
  const uploadFileChunks = async function (list) {
    if (list.length === 0) {
      //所有任务完成,合并切片
      mergeRequest({ filename: file.name }).then((res)=>{
        if(res.status==2000){

        }
      });
      return;
    }

    // 控制并发
    let pool = []; //并发池
    let finish = 0; //完成的数量
    let failList = []; //失败的列表

    for (let i = 0; i < list.length; i++) {
      let item = list[i];
      let formData = new FormData();

      formData.append("filename", file.name);
      formData.append("hash", item.hash);
      formData.append("chunk", item.chunk);
      // 上传切片
      let task = uploadRequest(formData);
      // console.log(formData);
      task
        .then((data) => {
          // 请求结束后将该Promise任务从并发池中移除
          let index = pool.findIndex((t) => t === task);
          pool.splice(index);
        })
        .catch(() => {
          console.log("错误", item.hash);
          failList.push(item);
        })
        .finally(() => {
          finish++;
          // 所有请求都请求完成
          if (finish === list.length) {
            console.log("所有请求都请求完成");
            uploadFileChunks(failList);
          }
        });
      pool.push(task);
      if (pool.length === concurrencyCount) {
        //每当并发池跑完一个任务，就再塞入一个任务
        await Promise.race(pool);
      }
    }
  };
  uploadFileChunks(fileChunks);
};
</script>

<template>
  <div>
    <el-upload
      :show-file-list="false"
      class="upload-demo"
      :http-request="filerequest"
      drag
      action
    >
      <Icon name="el-icon-Download" style="color: #3f7ff7" />
      <div class="el-upload__text">拖拽文件至此 或 <em>点击上传</em></div>
    </el-upload>
  </div>
</template>

<style scoped></style>
